package com.example.cookiedemo.config;

import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Configuration
public class CorsConfig {

    /**
     * 自定义CORS过滤器，实现不限制域名且允许携带cookie
     * 当设置allowCredentials=true时，不能使用通配符*作为allowedOrigin
     * 此过滤器会动态设置Access-Control-Allow-Origin为请求的Origin值
     */
    @Bean
    public Filter corsFilter() {
        return new Filter() {
            @Override
            public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
                HttpServletRequest httpRequest = (HttpServletRequest) request;
                HttpServletResponse httpResponse = (HttpServletResponse) response;

                // 获取请求的Origin头
                String origin = httpRequest.getHeader("Origin");

                // 如果有Origin头，则设置对应的响应头
                if (origin != null) {
                    httpResponse.setHeader("Access-Control-Allow-Origin", origin);
                }

                // 允许携带凭证（cookies）
                httpResponse.setHeader("Access-Control-Allow-Credentials", "true");
                // 允许的请求方法
                httpResponse.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS, PATCH");
                // 允许的请求头
                httpResponse.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Authorization, Cache-Control, Pragma");
                // 设置预检请求的有效期，单位为秒
                httpResponse.setHeader("Access-Control-Max-Age", "3600");

                // 处理预检请求
                if ("OPTIONS".equalsIgnoreCase(httpRequest.getMethod())) {
                    httpResponse.setStatus(HttpServletResponse.SC_OK);
                    return;
                }

                // 继续处理请求
                chain.doFilter(request, response);
            }

            @Override
            public void init(FilterConfig filterConfig) throws ServletException {}

            @Override
            public void destroy() {}
        };
    }

    /**
     * 注册过滤器到Spring容器
     */
    @Bean
    public FilterRegistrationBean corsFilterRegistration() {
        FilterRegistrationBean registration = new FilterRegistrationBean();
        registration.setFilter(corsFilter());
        registration.addUrlPatterns("/*");
        registration.setName("corsFilter");
        registration.setOrder(1); // 设置过滤器优先级，确保在其他过滤器之前执行
        return registration;
    }
}